package com.linkage.jz.bankruptcy.activity.Project;

import android.app.ActionBar;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.linkage.jz.bankruptcy.BankruptcyApp;
import com.linkage.jz.bankruptcy.Consts;
import com.linkage.jz.bankruptcy.R;
import com.linkage.jz.bankruptcy.activity.MainActivity;
import com.linkage.jz.bankruptcy.activity.Person.PersonSettingReadMeActivity;
import com.linkage.jz.bankruptcy.activity.Project.ZQUser.AddProxyUserActivity;
import com.linkage.jz.bankruptcy.activity.Project.ZQUser.ChangeToMeActivity;;
import com.linkage.jz.bankruptcy.activity.Project.ZQUser.CreateZQFristApplyActivity;
import com.linkage.jz.bankruptcy.activity.Project.ZQUser.DetailOper.ChangerLegalRepActivity;
import com.linkage.jz.bankruptcy.activity.Project.ZQUser.EditZQUserBaseInfoActivity;
import com.linkage.jz.bankruptcy.activity.Project.ZQUser.EditZQUserBaseInfo_ChangeActivity;
import com.linkage.jz.bankruptcy.activity.Project.ZQUser.EditZQUserBaseInfo_EditActivity;
import com.linkage.jz.bankruptcy.activity.Project.ZQUser.ZQUserDetailActivity;
import com.linkage.jz.bankruptcy.activity.RegistLogin.GetPwdOneActivity;
import com.linkage.jz.bankruptcy.activity.RegistLogin.PhoneLoginActivity;
import com.linkage.jz.bankruptcy.bean.MyProInfo;
import com.linkage.jz.bankruptcy.bean.ZQUserDetailAuthBaseInfo;
import com.linkage.jz.bankruptcy.bean.ZQUserDetailBaseInfo;
import com.linkage.jz.bankruptcy.bean.ZQUserInfo;
import com.linkage.jz.bankruptcy.event.RefreshEvent;
import com.linkage.jz.bankruptcy.fragment.Project.ZQUserConfirmListFrgment;
import com.linkage.jz.bankruptcy.fragment.Project.ZQUserToBeConfirmListFrgment;
import com.linkage.jz.bankruptcy.net.BaseSubscriber;
import com.linkage.jz.bankruptcy.net.Network;
import com.linkage.jz.bankruptcy.net.ToastUtil;
import com.linkage.jz.bankruptcy.utils.SPUtils;
import com.linkage.jz.bankruptcy.widget.CreateZQUserDialog;
import com.linkage.jz.bankruptcy.widget.CreateZQUserNoticeDialog;
import com.linkage.jz.bankruptcy.widget.LoginNoticeDialog;
import com.linkage.jz.bankruptcy.widget.PopupMenuPublicPro;
import com.linkage.jz.bankruptcy.widget.PopupMenuZQ;
import com.linkage.jz.bankruptcy.widget.PublicNoticeDialog;
import com.linkage.jz.bankruptcy.widget.ShapeLoadingDialog;
import com.linkage.seapeak.activity.message.MultiMessageHistoryActivity;
import com.linkage.seapeak.activity.message.MultiSelectActivity;
import com.linkage.seapeak.activity.message.ScreenUserActivity;
import com.linkage.seapeak.activity.message.ZQScreenUserActivity;
import com.linkage.seapeak.base.BaseActivity;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Random;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.Headers;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;


/**
 * A login screen that offers login via email/password.
 */
public class ZQUserListActivity extends BaseActivity implements OnClickListener {
    private static final String TAG = PersonSettingReadMeActivity.class.getSimpleName();
    private RelativeLayout rl_dcphGroup_topBtn01, rl_dcphGroup_topBtn02;
    private LinearLayout topBtnContainer;
    private ViewPager mViewPager;
    private TabPagerAdapter mPagerAdapter;
    ArrayList<Fragment> fragments = new ArrayList<Fragment>();
    private ShapeLoadingDialog shapeLoadingDialog;
    private CreateZQUserDialog createUserDialog;
    private CreateZQUserNoticeDialog createZQUserNoticeDialog;
    private static MyProInfo mInfo;
    private String isOpen;
    private PopupMenuZQ popupMenu;
    private TextView topBtn01,topBtn02,unread_count;
    private ZQUserDetailAuthBaseInfo mAuthBaseInfo;
    private int changeType = -1;

    //    TextView top_title;
    View top_back;
    ImageView top_mune;

    public static void start(Context context, MyProInfo info) {
        mInfo = info;
        Intent intent = new Intent(context, ZQUserListActivity.class);
        context.startActivity(intent);

    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setStatusBarMode(false);
        setContentView(R.layout.activity_pro_zquserlist);
        shapeLoadingDialog = new ShapeLoadingDialog(this);
        ActionBar bar = this.getActionBar();
        if (bar != null) {
            bar.hide();
        }
        initview();
        init();
        showMune = false;
        getData();

        EventBus.getDefault().register(this);
        popupMenu = new PopupMenuZQ(this);
    }

    int pageType = 1;

    public void showAddZQUser( ) {

        pageType = 1;
        createUserDialog = new CreateZQUserDialog(ZQUserListActivity.this, onClickListener);
        createUserDialog.show();

    }

    public void menuShow(Boolean flag) {

//        if(flag)
//        {
//            top_mune.setVisibility(View.VISIBLE);
//        }else{
//            top_mune.setVisibility(View.INVISIBLE);
//        }

    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(RefreshEvent event) {
        if (TextUtils.equals(event.getType(), RefreshEvent.ADDZQUSRFLOW)) {
            pageType = 1;
            createUserDialog = new CreateZQUserDialog(ZQUserListActivity.this, onClickListener);
            createUserDialog.show();
        }

        if(TextUtils.equals(event.getType(), RefreshEvent.ZQNOSHOWMENU)) {

        }

        if(TextUtils.equals(event.getType(), RefreshEvent.ZQSHOWMENU)) {

        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    //初始化视图
    private void initview() {
        //登录层、下拉层、其它登录方式层
        top_back = findViewById(R.id.top_back);
        top_mune = findViewById(R.id.top_mune);
        if (mInfo == null) {
            return;
        }
        if("".equalsIgnoreCase(mInfo.getmTeamId()))
        {
            top_mune.setVisibility(View.INVISIBLE);
        }

        top_mune.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                PopupMenuPublicPro popupMenu;
                ArrayList<String> ary = new ArrayList<String>();
                popupMenu = new PopupMenuPublicPro(ZQUserListActivity.this);
                if (mAuthBaseInfo != null) {


                    if (mAuthBaseInfo.isAddCreditor()) {
                        ary.add("添加债权人");
                    }
//                    if (mInfo.getAuth().isEditCreditorBasicInfo() || mInfo.getAuth().isEditCreditorBasicInfo()) {

                    if(mAuthBaseInfo.isCreditorInfoStatistics())
                        ary.add("债权人筛选");
//                    }
                    if (mAuthBaseInfo.isGroupSentMessage()) {
                        if( showMune) {
                            ary.add("群发消息");
                            ary.add("群发消息记录");
                        }
                    }

//                    if (ary.size() > 0) {

//                    } else {
//                        findViewById(R.id.menu_ddd).setVisibility(View.INVISIBLE);
//                    }

                }else {
//                    ary.add("债权人筛选");
                }
                popupMenu.initData(ary);


                popupMenu.showLocation(R.id.top_mune);// 设置弹出菜单弹出的位置


                // 设置回调监听，获取点击事件
                popupMenu.setOnItemClickListener(new PopupMenuPublicPro.OnItemClickListener() {

                    @Override
                    public void onClick(PopupMenuPublicPro.MENUITEM item, String str) {
                        if ("添加债权人".equalsIgnoreCase(str)) {
//                            convertOnlineStatus(2);
                            pageType = 1;
                            createUserDialog = new CreateZQUserDialog(ZQUserListActivity.this, onClickListener);
                            createUserDialog.show();
                        } else if ("债权人筛选".equalsIgnoreCase(str)) {
//                            convertOnlineStatus(1);
                            ZQScreenUserActivity.start(ZQUserListActivity.this,mInfo.getId());
                        } else if ("群发消息".equalsIgnoreCase(str)) {
//                            settingCommittee(2);
                            MultiSelectActivity.start(ZQUserListActivity.this, mInfo.getId());
                        } else if ("群发消息记录".equalsIgnoreCase(str)) {
//                            settingCommittee(1);
                            MultiMessageHistoryActivity.start(ZQUserListActivity.this, mInfo.getId());
                        }


//                    Toast.makeText(ZQUserDetailActivity.this,str,Toast.LENGTH_LONG).show();
                    }
                });
//            }
//                createUserDialog = new CreateUserDialog(ManagerListActivity.this,onClickListener);
//                createUserDialog.show();
//                popupMenu.showLocation(R.id.top_mune);// 设置弹出菜单弹出的位置
//                // 设置回调监听，获取点击事件
//                popupMenu.setOnItemClickListener(new PopupMenuZQ.OnItemClickListener() {
//
//                    @Override
//                    public void onClick(PopupMenuZQ.MENUITEM item, String str) {
//                        if (item == PopupMenuZQ.MENUITEM.ITEM1) {
//                            pageType = 1;
//                            createUserDialog = new CreateZQUserDialog(ZQUserListActivity.this, onClickListener);
//                            createUserDialog.show();
//                        } else if (item == PopupMenuZQ.MENUITEM.ITEM2) {
//                            //债权人筛选
////                            startActivityForResult(new Intent(ZQUserListActivity.this, ZQScreenUserActivity.class), 0x11);
//                            ZQScreenUserActivity.start(ZQUserListActivity.this,mInfo.getId());
//                        } else if (item == PopupMenuZQ.MENUITEM.ITEM3) {
//                            //群发消息
//                            MultiSelectActivity.start(ZQUserListActivity.this, mInfo.getId());
//                        } else if (item == PopupMenuZQ.MENUITEM.ITEM4) {
//                            //群发消息记录
//                            MultiMessageHistoryActivity.start(ZQUserListActivity.this, mInfo.getId());
//                        }
//                    }
//                });
//
            }
        }
        );
    }

    private OnClickListener onClickListener = new OnClickListener() {
        @Override
        public void onClick(View v) {

            switch (v.getId()) {

                case R.id.btn_chancel_zq_u:

                    if (pageType == 1) {
                        String name = createUserDialog.text_name_zq_u.getText().toString().trim();
                        String phone = createUserDialog.text_mobile_zq_u.getText().toString().trim();
                        if("".equalsIgnoreCase(name))
                        {
                            ToastUtil.showShort("请填写债权人姓名");
                            return;
                        }

//                        checkMobileInProject(name, phone, "","");
//                        addZQUser(name, phone, "","");
                        if("".equalsIgnoreCase(phone))
                        {
//                            checkMobileInProject(name, phone, "2","false");
                            addZQUser(name, phone, "2","false");
                        }else{
//                            checkMobileInProject(name, phone, "","");
                            addZQUser(name, phone, "","");
                        }

                    }
                    if (pageType == 2) {
                        String name = createUserDialog.text_name_zq_u.getText().toString().trim();
                        String phone = createUserDialog.text_mobile_zq_u.getText().toString().trim();
                        if("".equalsIgnoreCase(phone))
                        {
//                            checkMobileInProject(name, phone, "2","false");
                            addZQUser(name, phone, "2","false");
                        }else{
//                            checkMobileInProject(name, phone, "","");
                            addZQUser(name, phone, "","");
                        }
                        createZQUserNoticeDialog.dismiss();
                    }
                    break;
                case R.id.btn_save_zq_u:

                    if (pageType == 1) {
                        String name = createUserDialog.text_name_zq_u.getText().toString().trim();
                        String phone = createUserDialog.text_mobile_zq_u.getText().toString().trim();
                        if("".equalsIgnoreCase(name))
                        {
                            ToastUtil.showShort("请填写债权人姓名");
                            return;
                        }
                        checkMobileInProject(name, phone, "","");
//                        createUserDialog.dismiss();



                    } else if (pageType == 2) {
                        String name = createUserDialog.text_name_zq_u.getText().toString().trim();
                        String phone = createUserDialog.text_mobile_zq_u.getText().toString().trim();

                        String notifyType = "";
                        String flag = "false";
                        if (createZQUserNoticeDialog.ck_inmsg.isChecked()) {
                            notifyType = "0";
                        }

                        if (createZQUserNoticeDialog.ck_msg.isChecked()) {
                            if ("".equalsIgnoreCase(notifyType)) {
                                notifyType = "1";
                            } else {
                                notifyType = notifyType + ",1";
                            }
                        }

                        if (createZQUserNoticeDialog.ck_outmsg.isChecked()) {
                            if ("".equalsIgnoreCase(notifyType)) {
                                notifyType = "2";
                                if("".equalsIgnoreCase(phone))
                                {
                                    flag = "true";
                                }
                            } else {
                                notifyType = notifyType + ",2";
                            }
                        }

//                        checkMobileInProject(name, phone, notifyType,flag);
                        addZQUser(name, phone, notifyType,flag);

                        createZQUserNoticeDialog.dismiss();

                    }
                    break;

            }
        }
    };


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_login:
                //返回
                MainActivity.start(this);
                finish();
                break;
            case R.id.ll_phonelogin:
                PhoneLoginActivity.start(this);
                finish();
                break;
            case R.id.top_back:
                finish();
                break;
            case R.id.getPwd:
                GetPwdOneActivity.start(this);
            case R.id.rl_dcphGroup_topBtn01:
                changeFragmentFocus(0);
                mViewPager.setCurrentItem(0);
                break;
            case R.id.rl_dcphGroup_topBtn02:
                changeFragmentFocus(1);
                mViewPager.setCurrentItem(1);
                break;
            default:
                break;
        }
    }

    private void init() {
        top_back.setOnClickListener(this);

        ZQUserConfirmListFrgment groupChildrenCollect = new ZQUserConfirmListFrgment();
        ZQUserToBeConfirmListFrgment groupChildrenHasBuy = new ZQUserToBeConfirmListFrgment();
        Bundle bundle = new Bundle();
        if (mInfo == null || mInfo.getId() == null) {
            return;
        }

        bundle.putString("proid", mInfo.getId());//这里的values就是我们要传的值

        if(mInfo.getAuth()!=null) {
            try {
                bundle.putString("openAuth", mInfo.getAuth().getOpenAdministratorInfo() + "");//这里的values就是我们要传的值
            }catch (Exception ex)
            {
                ex.printStackTrace();
                bundle.putString("openAuth","true");
            }
        }else{
            bundle.putString("openAuth","true");
        }
        if(!"".equalsIgnoreCase(mInfo.getManagerId())  || !"".equalsIgnoreCase(mInfo.getOtherMemberId()))
        {
            bundle.putString("managerFlag","true");
        }else{
            bundle.putString("managerFlag","");
        }

        groupChildrenCollect.setArguments(bundle);

        groupChildrenHasBuy.setArguments(bundle);

        fragments.add(groupChildrenCollect);
        fragments.add(groupChildrenHasBuy);

        topBtn01 =findViewById(R.id.id_dcphGroup_topBtn01);
        topBtn02 =findViewById(R.id.id_dcphGroup_topBtn02);

        unread_count = findViewById(R.id.unread_count);
        rl_dcphGroup_topBtn01 = (RelativeLayout) this.findViewById(R.id.rl_dcphGroup_topBtn01);
        rl_dcphGroup_topBtn02 = (RelativeLayout) this.findViewById(R.id.rl_dcphGroup_topBtn02);
        topBtnContainer = (LinearLayout) this.findViewById(R.id.id_dcphGroup_topBtn_container);
        rl_dcphGroup_topBtn01.setOnClickListener(this);
        rl_dcphGroup_topBtn02.setOnClickListener(this);
        mViewPager = (ViewPager) this.findViewById(R.id.id_dcphGroup_viewPager);
        mPagerAdapter = new TabPagerAdapter(this.getSupportFragmentManager(), fragments);

        mViewPager.setAdapter(mPagerAdapter);
        mViewPager.invalidate();
        mPagerAdapter.notifyDataSetChanged();
    }

    /*
     * 自定义FragmentStatePagerAdapter适配器来显示滑动Fragment
     * */
    private class TabPagerAdapter extends FragmentStatePagerAdapter implements
            ViewPager.OnPageChangeListener {

        private ArrayList<Fragment> objects;

        public TabPagerAdapter(FragmentManager fm, ArrayList<Fragment> objects) {
            super(fm);
            this.objects = objects;
            mViewPager.setOnPageChangeListener(this);
        }

        @Override
        public Fragment getItem(int position) {
            return objects.get(position);
        }

        @Override
        public int getCount() {
            return objects.size();
        }

        @Override
        public void onPageScrollStateChanged(int arg0) {
        }

        @Override
        public void onPageScrolled(int position, float positionOffset,
                                   int positionOffsetPixels) {
        }

        @Override
        public void onPageSelected(int position) {
            //滑动的监听事件
            changeFragmentFocus(position);
        }
    }


    private void changeFragmentFocus(int focus) {
        if (focus == 0) {
//            topBtn01.setBackgroundResource(R.drawable.about_b_corner_btn);
//            topBtn02.setBackgroundResource(R.drawable.about_g_corner_btn);
            topBtn01.setTextColor(getResources().getColor(R.color.black));
            topBtn02.setTextColor(getResources().getColor(R.color.text_secondary_color));
        } else if (focus == 1) {
//            topBtn01.setBackgroundResource(R.drawable.about_g_corner_btn);
//            topBtn02.setBackgroundResource(R.drawable.about_b_corner_btn);
            topBtn01.setTextColor(getResources().getColor(R.color.text_secondary_color));
            topBtn02.setTextColor(getResources().getColor(R.color.black));
        }
    }


    public void addZQUser(String name, String phone, String notiytype,String mailed) {
        if (BankruptcyApp.tokeninfo == null || BankruptcyApp.tokeninfo.getToken() == null) {
            return;
        }
        shapeLoadingDialog.setLoadingText("加载中...");
        shapeLoadingDialog.setCanceledOnTouchOutside(false);
        shapeLoadingDialog.show();
        OkHttpClient okHttpClient = new OkHttpClient();
//        HashMap<String, String> params = new HashMap<String, String>();
        Random random = new Random();
        String rom = random.nextLong() + "";
        String timestamp = System.currentTimeMillis() + "";
        String userToken = SPUtils.getInstance(Consts.SPNAME).getString("userToken", "");
        String userId = SPUtils.getInstance(Consts.SPNAME).getString("userId", "");


        FormBody.Builder builder = new FormBody.Builder();

        builder.add("appid", Consts.appid);
        builder.add("nonce", rom);
        builder.add("timestamp", timestamp);
        builder.add("token", BankruptcyApp.tokeninfo.getToken());
        builder.add("userToken", userToken);
        builder.add("projectId", mInfo.getId());
        builder.add("creditorName", name);
        builder.add("mobile", phone);
        if(!"".equalsIgnoreCase(notiytype)) {
            builder.add("notifyType", notiytype);
        }
        if(!"".equalsIgnoreCase(mailed)) {
            builder.add("mailed", mailed);
        }


        RequestBody requestBody = builder.build();



        String url = Consts.WEBURL_ADDCREDITOR;
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();

        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                shapeLoadingDialog.dismiss();
                Log.d(TAG, "onFailure: " + e.getMessage());
                runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                        //更新UI
                        Toast.makeText(ZQUserListActivity.this, "保存失败", Toast.LENGTH_SHORT).show();

                    }

                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.d(TAG, response.protocol() + " " + response.code() + " " + response.message());
                Headers headers = response.headers();
                shapeLoadingDialog.dismiss();
                for (int i = 0; i < headers.size(); i++) {
                    Log.d(TAG, headers.name(i) + ":" + headers.value(i));
                }


                String str = response.body().string();
                try {
                    final JSONObject object = new JSONObject(str);
                    if  (object.optInt("code") == -10004 || (object.optInt("code") == -10003))
                    {

                        runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                LoginNoticeDialog.showPage(object.optString("msg"));
                            }

                        });

                        return;
                    }
                    if (object.optInt("code") == 0) {
                        runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                //更新UI
                                RefreshEvent event = new RefreshEvent();
                                event.setType(RefreshEvent.TYPE_ZQUSRE_LIST);
                                EventBus.getDefault().post(event);
                                getData();
                                Toast.makeText(ZQUserListActivity.this, "保存成功", Toast.LENGTH_SHORT).show();
                                createUserDialog.dismiss();
                            }

                        });
//                        finish();

                    } else {
                        runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                //更新UI
                                Toast.makeText(ZQUserListActivity.this, "保存失败" + object.optString("msg"), Toast.LENGTH_SHORT).show();

                            }

                        });

                    }
                    str = "";
                } catch (Exception ex) {
                    ex.printStackTrace();
                    runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            //更新UI
                            Toast.makeText(ZQUserListActivity.this, "保存失败", Toast.LENGTH_SHORT).show();

                        }

                    });
                }
            }
        });
    }

    public void flashMenu(){
        getData();
    }

    public void addUser(String groupId, String name, String phone) {
        if (BankruptcyApp.tokeninfo == null || BankruptcyApp.tokeninfo.getToken() == null) {
            return;
        }
        shapeLoadingDialog.setLoadingText("加载中...");
        shapeLoadingDialog.setCanceledOnTouchOutside(false);
        shapeLoadingDialog.show();
        OkHttpClient okHttpClient = new OkHttpClient();
//        HashMap<String, String> params = new HashMap<String, String>();
        Random random = new Random();
        String rom = random.nextLong() + "";
        String timestamp = System.currentTimeMillis() + "";
        String userToken = SPUtils.getInstance(Consts.SPNAME).getString("userToken", "");
        String userId = SPUtils.getInstance(Consts.SPNAME).getString("userId", "");

        RequestBody requestBody = new FormBody.Builder()
                .add("appid", Consts.appid)
                .add("nonce", rom)
                .add("timestamp", timestamp)
                .add("token", BankruptcyApp.tokeninfo.getToken())
                .add("userToken", userToken)


                .add("projectId", mInfo.getId())
                .add("groupId", groupId)
                .add("memberName", name)
                .add("memberMobile", phone)
                .build();

        String url = Consts.WEBURL_ADDMEMBER;
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();

        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                shapeLoadingDialog.dismiss();
                Log.d(TAG, "onFailure: " + e.getMessage());
                runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                        //更新UI
                        Toast.makeText(ZQUserListActivity.this, "保存失败", Toast.LENGTH_SHORT).show();

                    }

                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.d(TAG, response.protocol() + " " + response.code() + " " + response.message());
                Headers headers = response.headers();
                shapeLoadingDialog.dismiss();
                for (int i = 0; i < headers.size(); i++) {
                    Log.d(TAG, headers.name(i) + ":" + headers.value(i));
                }


                String str = response.body().string();
                try {
                    JSONObject object = new JSONObject(str);
                    if (object.optInt("code") == 0) {
                        runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                //更新UI
                                Toast.makeText(ZQUserListActivity.this, "保存成功", Toast.LENGTH_SHORT).show();
                                getData();
                            }

                        });
//                        finish();

                    } else {
                        runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                //更新UI
                                Toast.makeText(ZQUserListActivity.this, "保存失败", Toast.LENGTH_SHORT).show();

                            }

                        });

                    }
                    str = "";
                } catch (Exception ex) {
                    ex.printStackTrace();
                    runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            //更新UI
                            Toast.makeText(ZQUserListActivity.this, "保存失败", Toast.LENGTH_SHORT).show();

                        }

                    });
                }
            }
        });
    }


    private boolean showMune;
    public void getData()
    {
        if(BankruptcyApp.tokeninfo == null|| BankruptcyApp.tokeninfo.getToken() == null)
        {
            return;
        }
        shapeLoadingDialog.setLoadingText("加载中...");
        shapeLoadingDialog.setCanceledOnTouchOutside(false);
        shapeLoadingDialog.show();
        OkHttpClient okHttpClient = new OkHttpClient();
//        HashMap<String, String> params = new HashMap<String, String>();
        Random random = new Random();
        String rom = random.nextLong()+"";
        String timestamp =System.currentTimeMillis()+"";
        String userToken = SPUtils.getInstance(Consts.SPNAME).getString("userToken","");
        String userId = SPUtils.getInstance(Consts.SPNAME).getString("userId","");

//        final  String title = law_searchtxt.getText().toString();

        RequestBody requestBody = new FormBody.Builder()
                .add("appid","1000000001")
                .add("nonce",rom)
                .add("timestamp", timestamp)
                .add("projectId",mInfo.getId())
                .add("token", BankruptcyApp.tokeninfo.getToken())
                .add("userToken", userToken)
                .add("creditorName","")
                .add("process","0,1,2,3,4,5")
                .add("pageNo","1")
                .add("pageSize","5")
                .build();

        String url = Consts.WEBURL_CONFIRMEDLIST;
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();

        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                shapeLoadingDialog.dismiss();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {

                shapeLoadingDialog.dismiss();


                String str = response.body().string();

                try{


                    final JSONObject object = new JSONObject(str);
                    JSONObject dataobj = object.getJSONObject("data");
                    JSONObject dataobj5 = dataobj.getJSONObject("5");
                    JSONObject dataobj4 = dataobj.getJSONObject("4");
                    JSONObject dataobj3 = dataobj.getJSONObject("3");
                    JSONObject dataobj2 = dataobj.getJSONObject("2");
                    JSONObject dataobj1 = dataobj.getJSONObject("1");
                    JSONObject dataobj0 = dataobj.getJSONObject("0");

                    int count0 = 0;
                    int count1 = 0;
                    int count2 = 0;
                    int count3 = 0;
                    int count4 = 0;
                    int count5 = 0;
                    if(dataobj0!=null)
                    {
                        count0 = dataobj0.optInt("totalCount");
                    }
                    if(dataobj1!=null)
                    {
                        count1 = dataobj1.optInt("totalCount");
                    }
                    if(dataobj2!=null)
                    {
                        count2 = dataobj2.optInt("totalCount");
                    }
                    if(dataobj3!=null)
                    {
                        count3 = dataobj3.optInt("totalCount");
                    }
                    if(dataobj4!=null)
                    {
                        count4 = dataobj4.optInt("totalCount");
                    }
                    if(dataobj5!=null)
                    {
                        count5 = dataobj5.optInt("totalCount");
                    }

                    int count = count0+count1+count2+count3+count4+count5;
                    if(count == 0)
                    {
                        showMune = false;
                    }else{
                        showMune = true;
                    }

                    mAuthBaseInfo= new Gson().fromJson(dataobj.getJSONObject("auth").toString(), ZQUserDetailAuthBaseInfo.class);
//                    mInfo.setAuth(authBaseInfo);

                    if (mAuthBaseInfo.isAddCreditor() ||mAuthBaseInfo.isGroupSentMessage() ||mAuthBaseInfo.isCreditorInfoStatistics() ||showMune) {
                        top_mune.setVisibility(View.VISIBLE);
                    }else{
                        top_mune.setVisibility(View.GONE);
                    }
//                    if (mInfo.getAuth().isEditCreditorBasicInfo() || mInfo.getAuth().isEditCreditorBasicInfo()) {


                }catch (Exception ex)
                {
                    ex.printStackTrace();
                }
            }
        });
    }

    public void checkMobileInProject(final String name,final String phone,final String notiytype,final String mailed) {

        Observable<JsonObject> observable;

            observable = Network
                    .getAPIService()
                    .checkMobileInProject(getUserToken(),phone,mInfo.getId());


        observable
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<JsonObject>() {
                    @Override
                    public void onNext(JsonObject json) {

                        int code = json.get("code").getAsInt();

                        if(code == 0)
                        {
//                            addZQUser(name, phone, notiytype,mailed);
//                            createUserDialog.dismiss();
                            createZQUserNoticeDialog = new CreateZQUserNoticeDialog(ZQUserListActivity.this, onClickListener, name, phone);
                            createZQUserNoticeDialog.show();
                            pageType = 2;
                            createUserDialog.dismiss();
                        }else
                        {
                            ToastUtil.showShort(json.get("msg").getAsString());

                        }
                    }

                    @Override
                    public void onCompleted() {
                        super.onCompleted();
                    }

                    @Override
                    public void onError(Throwable e) {

                        super.onError(e);
                    }
                });
    }

    @Override
    protected void onResume() {
        super.onResume();
        countNeedVerify();
    }


    public void countNeedVerify() {

        Observable<JsonObject> observable;
        if(mInfo==null)
        {
            return;
        }

        observable = Network
                .getAPIService()
                .countNeedVerify(getUserToken(),mInfo.getId());


        observable
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<JsonObject>() {
                    @Override
                    public void onNext(JsonObject json) {

                        int code = json.get("code").getAsInt();

                        if(code == 0)
                        {
                            String data = json.get("data").getAsJsonObject().get("count").getAsString();

                            if(data!=null && !"0".equalsIgnoreCase(data))
                            {
                                unread_count.setVisibility(View.VISIBLE);
                                unread_count.setText("   "+data+"   ");
                            }else{
                                unread_count.setVisibility(View.GONE);
                            }
                        }else
                        {
//                            ToastUtil.showShort(json.get("msg").getAsString());

                        }
                    }

                    @Override
                    public void onCompleted() {
                        super.onCompleted();
                    }

                    @Override
                    public void onError(Throwable e) {

                        super.onError(e);
                    }
                });
    }

}


